// pages/check/check.ts
interface obj {
  goods_id: ''
  goods_img: ''
  goods_name: ''
  goods_price: number,
  quantity: number
}
interface Address {
  active: boolean;
  address: string;
  name: string;
  phone: string;
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    addArr: [] as obj[],
    seleted: 0,
    tatol: 0,
    cost: 0,
    payment: 0,
    isShow: false,
    selectedAddresses: [] as Address[],
    addresses: [
      { active: false, address: 'xx大学-xx楼-xxxx', name: 'xx先生', phone: '1xxxxxxxxxx' },
      { active: false, address: 'yy大学-yy楼-yyyy', name: 'yy女士', phone: '2xxxxxxxxxx' },
    ] as Address[]
  },
  jumpFn(){
    const { payment } = this.data;
    // console.log(111)
    // 存储最后一次的数据
    wx.setStorageSync('payment', payment)
    // ../pages/check/check
    wx.navigateTo({
      url: '../buymune/buymune'
    })
  },
  seletedFn() {
    this.setData({
      isShow: true
    })
  },
  forkFn() {
    this.setData({
      isShow: false
    })
  },
  toggleActive(e: { currentTarget: { dataset: { index: any; }; }; }) {
    const index = e.currentTarget.dataset.index; // 获取当前点击项的索引
    const addresses = this.data.addresses;
    const selectedAddresses = this.data.selectedAddresses
    // 切换 active 状态
    addresses.forEach((item, i) => {
      if (i === index) {
        item.active = !item.active; // 切换当前项的 active 状态
        if (item.active) {
          selectedAddresses.push(item); // 添加当前地址到新数组
        } else {
          const itemIndex = selectedAddresses.findIndex(addr => addr.address === item.address);
          if (itemIndex !== -1) {
            selectedAddresses.splice(itemIndex, 1); // 从数组中移除
          }
        }
      } else {
        item.active = false; // 只允许一个 active
      }
    });

    this.setData({ addresses, selectedAddresses }); // 更新数据
    console.log('Selected Addresses:', selectedAddresses); // 打印选中的地址

  },
  // 从本地存储获取数据的函数
  getStoredData() {
    try {
      const addArr = wx.getStorageSync('addArr') || [];
      const seleted = wx.getStorageSync('seleted') || 0;
      const cost = wx.getStorageSync('cost') || 0;
      const tatol = wx.getStorageSync('tatol') || 0;
      // console.log({addArr,seleted,cost,tatol})

      this.setData({
        addArr: addArr,
        seleted: seleted,
        cost: cost,
        tatol: tatol,
        payment: cost + tatol
      });
    } catch (e) {
      console.error('获取存储数据失败:', e);
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    this.getStoredData()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})